package org.aplikator.client.local.widgets;

import com.github.gwtbootstrap.client.ui.ListBox;
import com.google.gwt.event.dom.client.ChangeEvent;
import com.google.gwt.event.dom.client.ChangeHandler;
import com.google.gwt.event.logical.shared.ValueChangeHandler;
import com.google.gwt.event.shared.HandlerRegistration;
import org.aplikator.client.shared.data.ListItem;
import org.aplikator.client.shared.descriptor.PropertyDTO;

import java.io.Serializable;

public class ComboBoxWidget<T extends Serializable> extends DataFieldBase implements DataField<T> {
    private ListBox box = new ListBox(false);

    public ComboBoxWidget(String caption, PropertyDTO property, int size) {
        super(caption, property);
        for (ListItem item : property.getListValues()) {
            box.addItem(item.getName(), item.getValue().toString());
        }
        controls.add(box);
        //box.addStyleName(PaneWidgetResources.INSTANCE.css().formData());
        box.addChangeHandler(new ChangeHandler() {
            public void onChange(ChangeEvent event) {
                setDirty(true);
            }
        });
        if (size>0) {
            box.setSize(size);
        }
    }

    public void setValue(T value) {
        box.setSelectedIndex(-1);
        for (int i = 0; i < getProperty().getListValues().size(); i++) {
            if (((ListItem)getProperty().getListValues().get(i)).getValue().equals(value)) {
                box.setSelectedIndex(i);
                return;
            }
        }
        if (box.getSelectedIndex() >= 0) {
            box.setItemSelected(box.getSelectedIndex(), false);

        }
    }

    @SuppressWarnings("unchecked")
    public T getValue() {
        int index = box.getSelectedIndex();
        if (index == -1) {
            return null;
        }
        return (T) ((ListItem)getProperty().getListValues().get(index)).getValue();
    }

    public HandlerRegistration addValueChangeHandler(ValueChangeHandler<T> handler) {
        // return box.addChangeHandler(handler);
        return null;
    }

    public void setEnabled(boolean enabled) {
        box.setEnabled(enabled);
    }

}
